package com.hoshiicloud.saleorder.controller.sendorder;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.common.utils.BeanUtils;
import com.hoshiicloud.saleorder.entity.DispatchBill;
import com.hoshiicloud.saleorder.entity.DispatchBillDetail;
import com.hoshiicloud.saleorder.param.DispatchBillDetailAddParam;
import com.hoshiicloud.saleorder.param.DispatchBillDetailQueryParam;
import com.hoshiicloud.saleorder.param.DispatchBillDetailUpdateParam;
import com.hoshiicloud.saleorder.service.sendOrder.DispatchBillDetailService;
import com.hoshiicloud.saleorder.service.sendOrder.DispatchBillService;
import com.hoshiicloud.saleorder.vo.DisPatchBillDetailVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import javax.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author:campchen
 * @Date:Created in 下午 07:58 2019/8/22
 * @PACKAGENAME com.hoshiicloud.saleorder.controller.sendOrder
 * @Description
 */
@Slf4j
@RestController
@RequestMapping(value = "/orderSend/dispatchBillDetail")
@Api(value = "出库单详情", tags = {"出库单详情"})
public class DispatchBillDetailController {

    @Autowired
    private DispatchBillDetailService dispatchBillDetailService;

    @Autowired
    private DispatchBillService dispatchBillService;

    /**
     * @param param
     * @return com.hoshiicloud.common.rpc.Response
     * @description: 分页查询发货单明细
     */
    @ApiOperation(value = "分页查询发货单明细")
    @PostMapping("/getPage")
    public Response page(@RequestBody DispatchBillDetailQueryParam param) {
        try {
            QueryWrapper<DispatchBillDetail> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq((param.getDispatchBillId() != null && param.getDispatchBillId() != 0),
                    DispatchBillDetail::getDispatchBillId, param.getDispatchBillId())
                    .eq((param.getOrderId() != null && param.getOrderId() != 0), DispatchBillDetail::getOrderId,
                            param.getOrderId())
                    .eq((param.getSkuId() != null && param.getSkuId() != 0), DispatchBillDetail::getSkuId,
                            param.getSkuId())
                    .eq(StringUtils.isNotBlank(param.getSkuCode()), DispatchBillDetail::getSkuCode, param.getSkuCode())
                    .eq(StringUtils.isNotBlank(param.getSpuName()), DispatchBillDetail::getSpuName, param.getSpuName())
                    .eq(StringUtils.isNotBlank(param.getSpuSpec()), DispatchBillDetail::getSpuSpec, param.getSpuSpec())
                    .eq(StringUtils.isNotBlank(param.getSpuBarcode()), DispatchBillDetail::getSpuBarcode,
                            param.getSpuBarcode())
                    .eq(StringUtils.isNotBlank(param.getSpuCategory()), DispatchBillDetail::getSpuCategory,
                            param.getSpuCategory())
                    .eq((param.getQuantity() != null && param.getQuantity() != 0), DispatchBillDetail::getQuantity,
                            param.getQuantity())
                    .eq((param.getDeleted() != null && param.getDeleted() != 0), DispatchBillDetail::getDeleted,
                            param.getDeleted())
                    .eq(StringUtils.isNotBlank(param.getRemark()), DispatchBillDetail::getRemark, param.getRemark());
            Page<DispatchBillDetail> page = new Page<>(Long.parseLong(param.getPageNumber()),
                    Long.parseLong(param.getPageSize()));
            String key =
                    param.toString() + ",Page{pageNumber=" + param.getPageNumber() + ",pageSize=" + param.getPageSize()
                            + "}";
            return Response.data(dispatchBillDetailService.getPage(page, queryWrapper, key));
        } catch (Exception e) {
            log.error("分页查询发货单明细异常", e);
            return Response.failed("分页查询发货单明细异常");
        }
    }

    /**
     * @param id
     * @return com.hoshiicloud.common.rpc.Response
     * @description: 根据id查询发货单明细
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查询发货单明细")
    @ApiParam(name = "id", value = "主键ID", required = true)
    public Response queryById(@PathVariable("id") Long id) {
        return Response.data(dispatchBillDetailService.getById(id));
    }


    /**
     * @param param
     * @return com.hoshiicloud.common.rpc.Response
     * @description: 新增
     */
    @PostMapping("/save")
    @ApiOperation(value = "新增发货单明细")
    public Response save(@RequestBody @Valid DispatchBillDetailAddParam param) {
        DispatchBillDetail data;
        try {
            data = BeanUtils.covertType(param, DispatchBillDetail.class);
        } catch (Exception e) {
            log.error("新增机构发货单明细", e);
            return Response.failed("新增发货单明细 Bean转换异常");
        }
        return Response.data(dispatchBillDetailService.save(data));
    }


    /**
     * @param param
     * @return com.hoshiicloud.common.rpc.Response
     * @description: 修改发货单明细
     */
    @PutMapping("/update")
    @ApiOperation(value = "修改发货单明细")
    public Response update(@RequestBody @Valid DispatchBillDetailUpdateParam param) {
        DispatchBillDetail data;
        try {
            data = BeanUtils.covertType(param, DispatchBillDetail.class);
        } catch (Exception e) {
            log.error("修改发货单明细 Bean转换异常", e);
            return Response.failed("修改发货单明细 Bean转换异常");
        }
        return Response.data(dispatchBillDetailService.updateById(data));
    }

    @GetMapping("/getDispatchBillDetailList")
    @ApiOperation(value = "根据发货单ID查询发货单明细")
    @ApiImplicitParam(name = "dispatchId", value = "发货单ID", required = true, dataType = "Long", example = "3187243209717710848", paramType = "query")
    public Response getDispatchBillDetailList(@RequestParam("dispatchId") @Valid Long dispatchId) {
        QueryWrapper<DispatchBillDetail> dispatchBillDetailQueryWrapper = new QueryWrapper<>();
        dispatchBillDetailQueryWrapper.lambda()
                .eq(DispatchBillDetail::getDispatchBillId, dispatchId);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        DispatchBill dispatchBill = dispatchBillService.getById(dispatchId);
        LocalDateTime dispatchBillCreatedTime = dispatchBill.getCreatedTime();
        String dispatchBillCreatedTimeStr = dispatchBillCreatedTime.format(formatter);

        List<DispatchBillDetail> dispatchBillDetailList = dispatchBillDetailService.list(dispatchBillDetailQueryWrapper);
        dispatchBillDetailList.forEach(dispatchBillDetail -> {
            LocalDateTime dispatchBillDetailCreatedTime = dispatchBillDetail.getCreatedTime();
            dispatchBillDetailCreatedTime.format(formatter);
        });

        DisPatchBillDetailVo disPatchBillDetailVo = DisPatchBillDetailVo.builder()
                .consignee(dispatchBill.getConsignee())
                .consigneeAddress(dispatchBill.getConsigneeAddress())
                .consigneeTelephone(dispatchBill.getConsigneeTelephone())
                .createdName(dispatchBill.getCreatedBy())
                .createdTime(dispatchBillCreatedTimeStr)
                .dispatchBillDetailList(dispatchBillDetailList).build();

        return Response.data(disPatchBillDetailVo);
    }
}
